/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package lojavirtual.persistence;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.List;
import lojavirtual.model.Pedido;
import lojavirtual.util.ConnectionFactory;
import lojavirtual.util.HibernateUtil;
import org.hibernate.Session;

/**
 *
 * @author 710930
 */
public class PedidoDAO implements DAO<Pedido> {

    public void inserir(Pedido pedido) {
       Connection connection = ConnectionFactory.getConnection();

       try{

           String SQL = " INSERT INTO PEDIDO(CLIENTE, NUMERO, RUA, CIDADE, ESTADO, CEP) VALUES (?, ?, ?, ?, ? ,?) ";
           PreparedStatement statement = connection.prepareStatement(SQL);
           statement.setString(1, pedido.getUsuario().getLogin());
           statement.setString(2, pedido.getNumero());
           statement.setString(3, pedido.getRua());
           statement.setString(4, pedido.getCidade());
           statement.setString(5, pedido.getEstado());
           statement.setString(6, pedido.getCep());

           statement.executeUpdate();

       } catch (Exception e){ e.printStackTrace();}
       finally { ConnectionFactory.close(connection); }
    }

    public void alterar(Pedido pedido) {
       Connection connection = ConnectionFactory.getConnection();

       try{

           String SQL = "UPDATE PEDIDO (NUMERO, RUA, CIDADE, CEP) SET (?, ?, ?, ?) WHERE ID = ?";

           PreparedStatement statement = connection.prepareStatement(SQL);
           statement.setString(1, pedido.getNumero());
           statement.setString(2, pedido.getRua());
           statement.setString(3, pedido.getCidade());
           statement.setString(4, pedido.getCep());
           statement.setString(5, pedido.getUsuario().getLogin());
           statement.executeUpdate();

       } catch (Exception e){ e.printStackTrace();}
       finally { ConnectionFactory.close(connection); }
    }

    public List<Pedido> listar(Pedido pedido) {
        return null;
    }

    public void remover(Pedido pedido) {
       Connection connection = ConnectionFactory.getConnection();

       try{

           String SQL = "DELETE FROM PEDIDO WHERE ID = ?";

           PreparedStatement statement = connection.prepareStatement(SQL);
           statement.setInt(1, pedido.getId());
           statement.executeUpdate();

       } catch (Exception e){ e.printStackTrace();}
       finally { ConnectionFactory.close(connection); }
    }

    public List<Pedido> listarPedidos(){
        Session session = HibernateUtil.getSessionFactory().openSession();
        List<Pedido> categorias = session.createCriteria(Pedido.class).list();
        session.close();
        return categorias;
    }
}
